package priv.mill.controller;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import priv.mill.controller.util.RetenObj;
import priv.mill.entry.Question;
import priv.mill.server.QuestionService;

@Controller
@RequestMapping("Question")
public class QuestionController {

	@Autowired
	private QuestionService questionService;

	private static final Logger logger = Logger.getLogger(QuestionController.class);

	@RequestMapping("getQuestionById")
	@ResponseBody
	public RetenObj getQuestionById(@RequestParam("QuestionId") Integer questionId) {
		try {
			return warpData(questionService.getQuestionById(questionId), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	private RetenObj warpData(Object object, int i) {
		RetenObj retenObj = new RetenObj();
		retenObj.setData(object);
		retenObj.setStatus(i);
		return retenObj;
	}

	@RequestMapping("getQuestionByEntry")
	@ResponseBody
	public RetenObj getQuestionByEntry(Question question) {
		try {
			return warpData(questionService.getQuestionByEntry(question), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("getQuestionsByPage")
	@ResponseBody
	public RetenObj getQuestionsByPage(Question question) {
		try {
			return warpData(questionService.getQuestionsByPage(question), 200);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("updateQuestion")
	@ResponseBody
	public RetenObj updateQuestion(Question question) {
		try {
			int result = questionService.updateQuestion(question);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}
	

	@RequestMapping("insertQuestion")
	@ResponseBody
	public RetenObj insertQuestion(Question question) {
		try {
			int result = questionService.insertQuestion(question);
			if (result > 0)
				return warpData(question.getQId(), 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}
	}

	@RequestMapping("deleteQuestion")
	
	@ResponseBody
	public RetenObj deleteQuestion(Integer questionId) {
		try {
			int result = questionService.deleteQuestion(questionId);
			if (result > 0)
				return warpData(result, 200);
			else
				return warpData(result, 300);
		} catch (Exception e) {
			logger.error(e.getMessage());
			return warpData(null, 500);
		}

	}
}
